package com.jarvan.service.impl;

import com.alibaba.fastjson.JSON;
import com.jarvan.dto.TicketDto;
import com.jarvan.form.TicketForm;
import com.jarvan.model.Passenger;
import com.jarvan.model.Record;
import com.jarvan.model.Ticket;
import com.jarvan.model.Trains;
import com.jarvan.repository.TicketRepository;
import com.jarvan.service.TicketService;
import com.jarvan.utils.KeyUtil;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class TicketServiceImpl implements TicketService {

    @Autowired
    private TicketRepository repository;

    @Autowired
    private TrainsServiceImpl trainsService;

    @Autowired
    private PassengerServiceImpl passengerService;

    @Autowired
    private RecordServiceImpl recordService;

    @Override
    public TicketDto save(TicketForm ticketForm) {

        Ticket ticket = new Ticket();
        BeanUtils.copyProperties(ticketForm, ticket);
        String ticketId = KeyUtil.GenUniqueKey();
        ticket.setTicketId(ticketId);
        Trains trains = trainsService.findOne(ticketForm.getTrainId());
        ticket.setDepartureTime(trains.getStartTime());
        ticket.setDestinationTime(trains.getEndTime());
        List<String> stations = JSON.parseArray(trains.getStations(), String.class);
        int start = stations.indexOf(ticketForm.getDeparture());
        int end = stations.indexOf(ticketForm.getDestination());
        BigDecimal amount;
        amount = trains.getPersitePrice().multiply(new BigDecimal(end - start));
        ticket.setTicketAmount(amount);
        //TODO 生成座位号
//        Record record = new Record();
//        record.setBindTrain(ticketForm.getTrainId());
//        record.setDepartureDate(ticketForm.getDepartureDate());
//        int nextSeat =
//        record.setNextSeat();
        Record record = recordService.findByTrainId(ticketForm.getTrainId(), ticketForm.getDepartureDate());
        Record record1 = new Record();
        int carriage, seat;
        if (record != null){
            if ((record.getCurrCarriage() + 1) < trains.getCarriage()){
                if ((record.getNextSeat() + 1) > 60){
                    carriage = record.getCurrCarriage() + 1;
                    seat = 1;
                } else {
                    carriage = record.getCurrCarriage();
                    seat = record.getNextSeat() + 1;
                }
            } else {
                //TODO 统计重复座位
                List<Ticket> ticketList = repository.findAllByTrainIdAndDepartureDate(ticketForm.getTrainId(),
                        ticketForm.getDepartureDate());
                Ticket ticket1 = new Ticket();
                for (Ticket t: ticketList){
                    if (stations.indexOf(t.getDestination()) < stations.indexOf(ticketForm.getDeparture())){
                        ticket1 = t;
                         break;
                    }
                }
                carriage = ticket1.getCarriageNum();
                seat = ticket1.getSeatNum();
            }
        } else {
            record1.setBindTrain(ticketForm.getTrainId());
            record1 = recordService.save(record1);
            carriage = record1.getCurrCarriage();
            seat = record1.getNextSeat();
        }
        ticket.setCarriageNum(carriage);
        ticket.setSeatNum(seat);
        /*
         * 存入数据库
         */
        Ticket result =  repository.save(ticket);
        /*
         * 返回dtoc
         */
        return this.getDto(result, ticketForm.getBuyerId());
    }


    @Override
    public Ticket findById(String ticketId) {
        return repository.findById(ticketId).orElse(null);
    }

    @Override
    public Page<Ticket> findAllByTrainId(String trainId, Pageable pageable) {
        return repository.findAllByTrainId(trainId, pageable);
    }

    @Override
    public Page<Ticket> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public List<Ticket> findAllByBuyer(Integer buyerId) {
        return repository.findAllByBuyerId(buyerId);
    }

    @Override
    public List<Ticket> findAllByTrainAndDate(String trainId, String date) {
        return repository.findAllByTrainIdAndDepartureDate(trainId, date);
    }

    @Override
    public List<Ticket> findAllByBuyerAndStatus(Integer buyerId, Integer status) {
        return repository.findAllByBuyerIdAndTicketStatus(buyerId, status);
    }

    @Override
    public Page<Ticket> findAllByTicketStatus(Pageable pageable, Integer status) {
        return repository.findAllByTicketStatus(pageable, status);
    }

    @Override
    public void update(Ticket ticket) {
        repository.save(ticket);
    }

    @Override
    public Page<Ticket> findAllByBuyerId(Integer buyerId, Pageable pageable) {
        return repository.findAllByBuyerId(buyerId, pageable);
    }

    @Override
    public Page<Ticket> findAllByPayStatus(Integer payStatus, Pageable pageable) {
        return repository.findAllByPayStatus(payStatus, pageable);
    }

    public TicketDto getDto(Ticket ticket, Integer id){
        TicketDto dto = new TicketDto();
        BeanUtils.copyProperties(ticket, dto);
        Passenger passenger = passengerService.findById(id);
        dto.setIdentify(passenger.getIdentify());
        dto.setRealName(passenger.getRealName());
        return dto;
    }
}
